import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Tag,
  Input,
  Select,
  DatePicker,
  Modal,
  message,
  Popconfirm,
  Avatar,
  Typography,
  Row,
  Col,
  Statistic
} from 'antd';
import {
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  PlusOutlined,
  SearchOutlined,
  FileTextOutlined,
  CalendarOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { getArticlesAPI, deleteArticleAPI } from '../../apis/article';
import './Articles.scss';

const { Search } = Input;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { Text, Title } = Typography;

const Articles = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [articles, setArticles] = useState([]);
  const [filteredArticles, setFilteredArticles] = useState([]);
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [dateRange, setDateRange] = useState(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewArticle, setPreviewArticle] = useState(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  useEffect(() => {
    loadArticles();
  }, []);

  useEffect(() => {
    filterArticles();
  }, [articles, searchText, statusFilter, dateRange]);

  const loadArticles = async (params = {}) => {
    setLoading(true);
    try {
      const queryParams = {
        page: pagination.current,
        limit: pagination.pageSize,
        status: statusFilter === 'all' ? undefined : statusFilter,
        search: searchText || undefined,
        ...params
      };

      const response = await getArticlesAPI(queryParams);
      
      if (response.success) {
        const { articles: articleList, pagination: paginationData } = response.data;
        setArticles(articleList);
        setPagination(prev => ({
          ...prev,
          total: paginationData.total,
          current: paginationData.page
        }));
      } else {
        message.error(response.message || '加载作品失败');
      }
    } catch (error) {
      console.error('加载作品失败:', error);
      message.error('加载作品失败');
    } finally {
      setLoading(false);
    }
  };

  const filterArticles = () => {
    let filtered = [...articles];

    // 搜索过滤
    if (searchText) {
      filtered = filtered.filter(article =>
        article.title.toLowerCase().includes(searchText.toLowerCase()) ||
        article.excerpt.toLowerCase().includes(searchText.toLowerCase())
      );
    }

    // 状态过滤
    if (statusFilter !== 'all') {
      filtered = filtered.filter(article => article.status === statusFilter);
    }

    // 日期范围过滤
    if (dateRange && dateRange.length === 2) {
      const [startDate, endDate] = dateRange;
      filtered = filtered.filter(article => {
        const articleDate = new Date(article.createdAt);
        return articleDate >= startDate && articleDate <= endDate;
      });
    }

    setFilteredArticles(filtered);
  };

  const handleEdit = (record) => {
    navigate(`/works?id=${record.id}`);
  };

  const handleDelete = async (record) => {
    try {
      const response = await deleteArticleAPI(record.id);
      if (response.success) {
        message.success('作品删除成功');
        loadArticles(); // 重新加载列表
      } else {
        message.error(response.message || '删除失败');
      }
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  };

  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的作品');
      return;
    }

    Modal.confirm({
      title: '批量删除确认',
      content: `确定要删除选中的 ${selectedRowKeys.length} 篇作品吗？`,
      onOk: async () => {
        try {
          // 批量删除API调用
          const deletePromises = selectedRowKeys.map(id => deleteArticleAPI(id));
          await Promise.all(deletePromises);
          
          setSelectedRowKeys([]);
          message.success('批量删除成功');
          loadArticles(); // 重新加载列表
        } catch (error) {
          console.error('批量删除失败:', error);
          message.error('批量删除失败');
        }
      }
    });
  };

  const handlePreview = (record) => {
    setPreviewArticle(record);
    setPreviewVisible(true);
  };

  const handleStatusChange = async (record, newStatus) => {
    try {
      // 这里需要调用更新API
      // const response = await updateArticleAPI(record.id, { status: newStatus });
      // if (response.success) {
        setArticles(prev =>
          prev.map(item =>
            item.id === record.id
              ? { ...item, status: newStatus, updated_at: new Date().toISOString() }
              : item
          )
        );
        message.success(`作品已${newStatus === 'published' ? '发布' : '更新状态'}`);
      // } else {
      //   message.error(response.message || '状态更新失败');
      // }
    } catch (error) {
      console.error('状态更新失败:', error);
      message.error('状态更新失败');
    }
  };

  const getStatusColor = (status) => {
    const colors = {
      published: 'green',
      draft: 'orange',
      archived: 'red'
    };
    return colors[status] || 'default';
  };

  const getStatusText = (status) => {
    const texts = {
      published: '已发布',
      draft: '草稿',
      archived: '已归档'
    };
    return texts[status] || status;
  };

  const columns = [
    {
      title: '作品',
      dataIndex: 'title',
      key: 'title',
      width: 300,
      render: (text, record) => (
        <div className="article-info">
          <div className="article-header">
            <Avatar
              src={record.cover_image}
              shape="square"
              size={40}
              icon={<FileTextOutlined />}
            />
            <div className="article-details">
              <div 
                className="article-title" 
                title={text}
                style={{ cursor: 'pointer', color: '#1890ff' }}
                onClick={() => navigate(`/article-detail/${record.id}`)}
              >
                {text}
              </div>
              <div className="article-excerpt">
                {record.content_html ? 
                  record.content_html.replace(/<[^>]*>/g, '').substring(0, 100) + '...' : 
                  '暂无内容'
                }
              </div>
              <div className="article-author">
                作者: {record.username || '未知'}
              </div>
            </div>
          </div>
        </div>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status, record) => (
        <Select
          value={status}
          size="small"
          style={{ width: 80 }}
          onChange={(value) => handleStatusChange(record, value)}
        >
          <Option value="draft">草稿</Option>
          <Option value="published">发布</Option>
          <Option value="archived">归档</Option>
        </Select>
      ),
    },
    {
      title: '数据',
      key: 'stats',
      width: 150,
      render: (_, record) => (
        <Space direction="vertical" size="small">
          <Space size="middle">
            <Text type="secondary">
              <EyeOutlined /> {record.view_count || 0}
            </Text>
          </Space>
        </Space>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 120,
      render: (text) => (
        <Text type="secondary">
          {new Date(text).toLocaleDateString()}
        </Text>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => navigate(`/article-detail/${record.id}`)}
          >
            查看
          </Button>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这篇作品吗？"
            onConfirm={() => handleDelete(record)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
  };

  const stats = {
    total: articles.length,
    published: articles.filter(a => a.status === 'published').length,
    draft: articles.filter(a => a.status === 'draft').length,
    archived: articles.filter(a => a.status === 'archived').length,
  };

  return (
    <div className="articles-container">
      {/* 统计卡片 */}
      <Row gutter={[16, 16]} className="stats-row">
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="总作品数"
              value={stats.total}
              prefix={<FileTextOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="已发布"
              value={stats.published}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="草稿"
              value={stats.draft}
              valueStyle={{ color: '#fa8c16' }}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="已归档"
              value={stats.archived}
              valueStyle={{ color: '#f5222d' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 作品列表 */}
      <Card>
        <div className="table-header">
          <div className="header-left">
            <Title level={4} style={{ margin: 0 }}>
              作品管理
            </Title>
          </div>
          <div className="header-right">
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => navigate('/works')}
            >
              创建作品
            </Button>
          </div>
        </div>

        <div className="table-filters">
          <Row gutter={[16, 16]} align="middle">
            <Col xs={24} sm={8}>
              <Search
                placeholder="搜索作品标题或内容"
                allowClear
                onSearch={(value) => {
                  setSearchText(value);
                  setPagination(prev => ({ ...prev, current: 1 }));
                  loadArticles({ page: 1, search: value });
                }}
                onChange={(e) => {
                  if (!e.target.value) {
                    setSearchText('');
                    loadArticles({ page: 1, search: '' });
                  }
                }}
              />
            </Col>
            <Col xs={12} sm={4}>
              <Select
                placeholder="状态筛选"
                value={statusFilter}
                onChange={(value) => {
                  setStatusFilter(value);
                  setPagination(prev => ({ ...prev, current: 1 }));
                  loadArticles({ page: 1, status: value === 'all' ? undefined : value });
                }}
                style={{ width: '100%' }}
              >
                <Option value="all">全部状态</Option>
                <Option value="published">已发布</Option>
                <Option value="draft">草稿</Option>
                <Option value="archived">已归档</Option>
              </Select>
            </Col>
            <Col xs={12} sm={6}>
              <RangePicker
                placeholder={['开始日期', '结束日期']}
                onChange={setDateRange}
                style={{ width: '100%' }}
              />
            </Col>
            <Col xs={24} sm={6}>
              <Space>
                {selectedRowKeys.length > 0 && (
                  <Button
                    danger
                    onClick={handleBatchDelete}
                  >
                    批量删除 ({selectedRowKeys.length})
                  </Button>
                )}
                <Button
                  icon={<SearchOutlined />}
                  onClick={loadArticles}
                >
                  刷新
                </Button>
              </Space>
            </Col>
          </Row>
        </div>

        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={articles}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
            onChange: (page, pageSize) => {
              setPagination(prev => ({ ...prev, current: page, pageSize }));
              loadArticles({ page, limit: pageSize });
            }
          }}
        />
      </Card>

      {/* 预览模态框 */}
      <Modal
        title="作品预览"
        open={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        footer={[
          <Button key="edit" type="primary" onClick={() => {
            setPreviewVisible(false);
            handleEdit(previewArticle);
          }}>
            编辑作品
          </Button>,
          <Button key="close" onClick={() => setPreviewVisible(false)}>
            关闭
          </Button>
        ]}
        width="80%"
      >
        {previewArticle && (
          <div className="article-preview">
            <div className="preview-header">
              <Title level={2}>{previewArticle.title}</Title>
              <Space>
                <Tag color={getStatusColor(previewArticle.status)}>
                  {getStatusText(previewArticle.status)}
                </Tag>
                <Text type="secondary">
                  <CalendarOutlined /> {previewArticle.createdAt}
                </Text>
              </Space>
            </div>
            <div className="preview-content">
              <p>{previewArticle.excerpt}</p>
              <p>这里是作品的完整内容预览...</p>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default Articles;